<!--
  智慧社区管理系统 - 设备监控
  @author Wu.Liang
  @date 2025-01-20
  @description 设备监控页面，展示IoT设备实时状态、数据监控、告警管理等功能
-->
<template>
  <div class="device-monitor-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon class="title-icon"><Monitor /></el-icon>
          设备监控
        </h2>
        <p class="page-description">实时监控社区IoT设备运行状态，及时发现和处理设备异常</p>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Refresh" @click="handleRefresh" :loading="refreshing">
          刷新数据
        </el-button>
        <el-button type="success" :icon="Setting" @click="handleSettings">
          监控设置
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-icon online">
                <el-icon><Connection /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ deviceStats.onlineCount }}</div>
                <div class="stats-label">在线设备</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-icon offline">
                <el-icon><CloseBold /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ deviceStats.offlineCount }}</div>
                <div class="stats-label">离线设备</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-icon warning">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ deviceStats.warningCount }}</div>
                <div class="stats-label">告警设备</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><DataBoard /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ deviceStats.totalCount }}</div>
                <div class="stats-label">设备总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="设备类型">
          <el-select v-model="searchForm.deviceType" placeholder="请选择设备类型" clearable style="width: 150px">
            <el-option label="门禁设备" :value="1" />
            <el-option label="监控设备" :value="2" />
            <el-option label="照明设备" :value="3" />
            <el-option label="电梯设备" :value="4" />
            <el-option label="消防设备" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="运行状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="在线" :value="1" />
            <el-option label="离线" :value="0" />
            <el-option label="告警" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置">
          <el-input v-model="searchForm.location" placeholder="请输入安装位置" style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备列表 -->
    <el-card class="device-list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">设备监控列表</span>
          <div class="header-actions">
            <el-button type="primary" :icon="Plus" @click="handleAddDevice">新增设备</el-button>
            <el-button :icon="Download" @click="handleExport">导出数据</el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="deviceList" 
        v-loading="loading" 
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="deviceName" label="设备名称" min-width="150">
          <template #default="{ row }">
            <div class="device-name">
              <el-icon class="device-icon" :class="getDeviceIconClass(row.deviceType)">
                <component :is="getDeviceIcon(row.deviceType)" />
              </el-icon>
              <span>{{ row.deviceName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="deviceType" label="设备类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getDeviceTypeTagType(row.deviceType)" size="small">
              {{ getDeviceTypeName(row.deviceType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="location" label="安装位置" min-width="150" />
        
        <el-table-column prop="status" label="运行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="lastUpdateTime" label="最后更新时间" width="180" />
        
        <el-table-column prop="alarmCount" label="告警次数" width="100">
          <template #default="{ row }">
            <el-badge :value="row.alarmCount" :hidden="row.alarmCount === 0" type="danger">
              <span>{{ row.alarmCount }}</span>
            </el-badge>
          </template>
        </el-table-column>
        
        <el-table-column prop="batteryLevel" label="电量" width="100">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.batteryLevel" 
              :color="getBatteryColor(row.batteryLevel)"
              :stroke-width="8"
              :show-text="false"
            />
            <span class="battery-text">{{ row.batteryLevel }}%</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button size="small" type="success" @click="handleControl(row)">控制</el-button>
            <el-button size="small" type="warning" @click="handleConfig(row)">配置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 设备详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="设备详情" 
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="device-detail" v-if="currentDevice">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ currentDevice.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ getDeviceTypeName(currentDevice.deviceType) }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ currentDevice.deviceCode }}</el-descriptions-item>
          <el-descriptions-item label="安装位置">{{ currentDevice.location }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getStatusTagType(currentDevice.status)">
              {{ getStatusName(currentDevice.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="电量">{{ currentDevice.batteryLevel }}%</el-descriptions-item>
          <el-descriptions-item label="最后更新时间">{{ currentDevice.lastUpdateTime }}</el-descriptions-item>
          <el-descriptions-item label="告警次数">{{ currentDevice.alarmCount }}</el-descriptions-item>
          <el-descriptions-item label="设备描述" :span="2">{{ currentDevice.description || '暂无描述' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditDevice">编辑设备</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { 
  Monitor, 
  Refresh, 
  Setting, 
  Connection, 
  CloseBold, 
  Warning, 
  DataBoard,
  Search,
  Plus,
  Download,
  VideoCamera,
  Lock,
  Sunny,
  ArrowUp,
  CircleClose
} from '@element-plus/icons-vue'
import { showMessage } from '@/utils/message'

// 响应式数据
const loading = ref(false)
const refreshing = ref(false)
const detailDialogVisible = ref(false)
const currentDevice = ref<any>(null)

// 搜索表单
const searchForm = reactive({
  deviceType: undefined as number | undefined,
  status: undefined as number | undefined,
  location: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 设备统计数据
const deviceStats = reactive({
  onlineCount: 156,
  offlineCount: 8,
  warningCount: 3,
  totalCount: 167
})

// 设备列表数据
const deviceList = ref([
  {
    id: 1,
    deviceName: '1号楼门禁',
    deviceCode: 'MJ001',
    deviceType: 1,
    location: '1号楼大厅',
    status: 1,
    lastUpdateTime: '2025-01-20 15:30:25',
    alarmCount: 0,
    batteryLevel: 85,
    description: '1号楼大厅门禁设备，支持刷卡、人脸识别'
  },
  {
    id: 2,
    deviceName: '社区监控摄像头',
    deviceCode: 'JK002',
    deviceType: 2,
    location: '社区大门',
    status: 1,
    lastUpdateTime: '2025-01-20 15:29:18',
    alarmCount: 2,
    batteryLevel: 92,
    description: '社区大门监控摄像头，24小时监控'
  },
  {
    id: 3,
    deviceName: '地下车库照明',
    deviceCode: 'ZM003',
    deviceType: 3,
    location: '地下车库',
    status: 0,
    lastUpdateTime: '2025-01-20 14:15:30',
    alarmCount: 1,
    batteryLevel: 45,
    description: '地下车库照明控制系统'
  },
  {
    id: 4,
    deviceName: '2号楼电梯',
    deviceCode: 'DT004',
    deviceType: 4,
    location: '2号楼',
    status: 2,
    lastUpdateTime: '2025-01-20 15:25:10',
    alarmCount: 3,
    batteryLevel: 78,
    description: '2号楼客梯设备'
  },
  {
    id: 5,
    deviceName: '消防报警器',
    deviceCode: 'XF005',
    deviceType: 5,
    location: '3号楼',
    status: 1,
    lastUpdateTime: '2025-01-20 15:28:45',
    alarmCount: 0,
    batteryLevel: 95,
    description: '3号楼消防报警系统'
  }
])

// 计算属性
const getDeviceTypeName = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: '门禁设备',
    2: '监控设备',
    3: '照明设备',
    4: '电梯设备',
    5: '消防设备'
  }
  return typeMap[type] || '未知设备'
}

const getDeviceTypeTagType = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info',
    5: 'danger'
  }
  return typeMap[type] || 'info'
}

const getDeviceIcon = (type: number) => {
  const iconMap: Record<number, any> = {
    1: Lock,
    2: VideoCamera,
    3: Sunny,
    4: ArrowUp,
    5: CircleClose
  }
  return iconMap[type] || Monitor
}

const getDeviceIconClass = (type: number): string => {
  return `device-icon-${type}`
}

const getStatusName = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '离线',
    1: '在线',
    2: '告警'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  }
  return statusMap[status] || 'info'
}

const getBatteryColor = (level: number): string => {
  if (level >= 80) return '#67C23A'
  if (level >= 60) return '#E6A23C'
  if (level >= 40) return '#F56C6C'
  return '#F56C6C'
}

// 方法
const handleRefresh = async () => {
  refreshing.value = true
  try {
    // 模拟刷新数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    showMessage({ type: 'success', message: '数据刷新成功' })
  } catch (error) {
    showMessage({ type: 'error', message: '数据刷新失败' })
  } finally {
    refreshing.value = false
  }
}

const handleSettings = () => {
  showMessage({ type: 'info', message: '监控设置功能开发中' })
}

const handleSearch = () => {
  pagination.current = 1
  loadDeviceList()
}

const handleReset = () => {
  searchForm.deviceType = undefined
  searchForm.status = undefined
  searchForm.location = ''
  pagination.current = 1
  loadDeviceList()
}

const handleAddDevice = () => {
  showMessage({ type: 'info', message: '新增设备功能开发中' })
}

const handleExport = () => {
  showMessage({ type: 'info', message: '导出功能开发中' })
}

const handleDetail = (row: any) => {
  currentDevice.value = row
  detailDialogVisible.value = true
}

const handleControl = (row: any) => {
  showMessage({ type: 'info', message: `设备控制功能开发中 - ${row.deviceName}` })
}

const handleConfig = (row: any) => {
  showMessage({ type: 'info', message: `设备配置功能开发中 - ${row.deviceName}` })
}

const handleEditDevice = () => {
  showMessage({ type: 'info', message: '编辑设备功能开发中' })
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadDeviceList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadDeviceList()
}

const getRowClassName = ({ row }: { row: any }) => {
  if (row.status === 2) return 'warning-row'
  if (row.status === 0) return 'offline-row'
  return ''
}

const loadDeviceList = () => {
  loading.value = true
  // 模拟加载数据
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadDeviceList()
})
</script>

<style scoped lang="scss">
.device-monitor-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;

    .header-left {
      .page-title {
        margin: 0 0 8px 0;
        font-size: 28px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 12px;

        .title-icon {
          font-size: 32px;
        }
      }

      .page-description {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .stats-cards {
    margin-bottom: 24px;

    .stats-card {
      .stats-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stats-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          color: white;

          &.online {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }

          &.offline {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }

          &.warning {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.total {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }

        .stats-info {
          .stats-number {
            font-size: 32px;
            font-weight: 700;
            color: #303133;
            line-height: 1;
          }

          .stats-label {
            font-size: 14px;
            color: #909399;
            margin-top: 4px;
          }
        }
      }
    }
  }

  .search-card {
    margin-bottom: 24px;
    border-radius: 8px;
  }

  .device-list-card {
    border-radius: 8px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }

      .header-actions {
        display: flex;
        gap: 12px;
      }
    }

    .device-name {
      display: flex;
      align-items: center;
      gap: 8px;

      .device-icon {
        font-size: 16px;
        color: #409eff;

        &.device-icon-1 { color: #409eff; }
        &.device-icon-2 { color: #67c23a; }
        &.device-icon-3 { color: #e6a23c; }
        &.device-icon-4 { color: #909399; }
        &.device-icon-5 { color: #f56c6c; }
      }
    }

    .battery-text {
      margin-left: 8px;
      font-size: 12px;
      color: #909399;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }

  .device-detail {
    .el-descriptions {
      margin-bottom: 16px;
    }
  }
}

// 表格行样式
:deep(.warning-row) {
  background-color: #fdf6ec;
}

:deep(.offline-row) {
  background-color: #fef0f0;
}

// 响应式设计
@media (max-width: 768px) {
  .device-monitor-container {
    padding: 12px;

    .page-header {
      flex-direction: column;
      gap: 16px;

      .header-right {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .stats-cards {
      .el-col {
        margin-bottom: 16px;
      }
    }
  }
}
</style> 